﻿namespace SchoolSystem.Server.Controllers
{
    using System;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using System.Web.Http.ValueProviders;
    using SchoolSystem.Data;
    using SchoolSystem.Server.AuthenticationHeaders;
    using SchoolSystem.Server.Models;

    public class StudentsController : BaseApiController<Student>
    {
        [HttpGet]
        public HttpResponseMessage GetPersonalData([ValueProvider(typeof(HeaderValueProviderFactory<string>))]
                                                   string accessToken)
        {
            return this.ExecuteOperationAndHandleExceptions(() =>
            {
                if (accessToken == null)
                {
                    throw new ArgumentNullException("Invalid access token");
                }

                var account = this.GetAccountByAccessToken(accessToken);

                var studentModel = this.data.All()
                                       .Where(s => s.Account.AccountId == account.AccountId)
                                       .Select(StudentFullModel.FromStudent)
                                       .FirstOrDefault();

                if (studentModel == null)
                {
                    throw new ArgumentException("No such student for this account");
                }

                var response = this.Request.CreateResponse(HttpStatusCode.OK, studentModel);

                return response;
            });
        }

        [HttpGet]
        [ActionName("disciplines")]
        public HttpResponseMessage GetDiscipline(
            [ValueProvider(typeof(HeaderValueProviderFactory<string>))]
            string accessToken,
            [FromUri]
            int id)
        {
            return this.ExecuteOperationAndHandleExceptions(() =>
            {
                if (accessToken == null)
                {
                    throw new ArgumentNullException("Invalid access token");
                }

                var account = this.GetAccountByAccessToken(accessToken);

                var student = account.Students
                                     .AsQueryable()
                                     .FirstOrDefault(s => s.AccountId == account.AccountId);

                if (student == null)
                {
                    throw new ArgumentException("No such student for this account");
                }

                var disciplineModel = student.Class
                                              .Disciplines
                                              .AsQueryable()
                                              .Where(d => d.DisciplineId == id).Select(DisciplineForStudentModel.FromDiscipline);


                var response = this.Request.CreateResponse(HttpStatusCode.OK, disciplineModel);

                return response;
            });
        }
    }
}